﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using KBManagement.DAL;
using KBManagement.BIZ;
using KBManagement.Library;

namespace KBManagement
{
    public partial class EmployeeManagement : Form,InforObserver
    {
        KBSQLClassDataContext context;
        TransactionLog transactionLog;
        TimeSlotFacade timeSlotFacade;
        EmployeeFacade employeeFacade;
        IQueryable detailPenalty;
        IQueryable employeeQuery;
        int dgvEmployeeIndex = 0;
        int grvTimeSlotIndex = 0;
        public EmployeeManagement()
        {
            timeSlotFacade = new TimeSlotFacade();
            transactionLog = new TransactionLog();
            employeeFacade = new EmployeeFacade();
            context = Utils.CreateInstance().GetDBContext();
            InitializeComponent();
            Utils.CreateInstance().AddInforObserver(this);
            dtpFrom.Value = DateTime.Now.AddMonths(-1);
            SelectEmployee();
            SelectTimeSlot();
            SelectDetailPenalty();
            BindingComboBox();
        }

        private void BindingComboBox()
        {
            var penaty = from fc in context.Penalties select fc;
            cbbNamePenalty.DataSource=penaty;
            cbbNamePenalty.DisplayMember = "Pe_Name";
            cbbNamePenalty.ValueMember = "ID";
        }

        private void SelectFood()
        {
            var food = from fc in context.Employees select new 
            {
            fc.ID,
            fc.FullName,
            fc.Email,
            fc.Address,
            fc.BirthDay,
            fc.Gender,
            fc.Phone,
            fc.Position.Ps_Name,
            fc.TimeSlot.StartTime,
            fc.TimeSlot.EndTime
            };
            dgvEmployee.DataSource = food;
            dgvEmployee.Columns[0].HeaderText = "Mã số";
            dgvEmployee.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            dgvEmployee.Columns[1].HeaderText = "Họ tên";
            dgvEmployee.Columns[2].HeaderText = "Thư điện tử";
            dgvEmployee.Columns[3].HeaderText = "Địa chỉ";
            dgvEmployee.Columns[4].HeaderText = "Ngày sinh";
            dgvEmployee.Columns[5].HeaderText = "Giới tính";
            dgvEmployee.Columns[6].HeaderText = "Điện thoại";
            dgvEmployee.Columns[7].HeaderText = "Chức vụ";
            dgvEmployee.Columns[8].HeaderText = "Giờ bắt đầu ca";
            dgvEmployee.Columns[9].HeaderText = "Giờ kết thúc ca";

            employeeQuery = from fc in context.Employees select fc;
        }

        private void SelectDetailPenalty()
        {
           var detailPenal = from fc in context.Penalty_Details
                            select new
                            {
                                fc.ID,
                                fc.Pay_Salary.Employee.FullName,
                                fc.Description,
                                fc.Status,
                                fc.PenaltyDate,
                                fc.Penalty.Pe_Name
                            }
            ;
           dataGridView4.DataSource = detailPenal;
           SetHeaderDetailPenalty();
           detailPenalty = from fc in context.Penalty_Details select fc;
        }

        private void SearchDetailPenalty(string name, DateTime dateFrom, DateTime dateTo)
        {
            var detailPena = from fc in context.Penalty_Details
                                where fc.Pay_Salary.Employee.FullName.Contains(name) && fc.PenaltyDate >=dateFrom.AddDays(-1) && fc.PenaltyDate<=dateTo
                                select new
                                {
                                   fc.ID,
                                   fc.Pay_Salary.Employee.FullName,
                                   fc.Description,
                                   fc.Status,
                                   fc.PenaltyDate,
                                   fc.Penalty.Pe_Name
                                }
            ;
            dataGridView4.DataSource = detailPena;
            SetHeaderDetailPenalty();


            detailPenalty = from fc in context.Penalty_Details
                            where fc.Pay_Salary.Employee.FullName.Contains(name) && fc.PenaltyDate >= dateFrom && fc.PenaltyDate <= dateTo
                            select fc;
        }

        private void SelectTimeSlot()
        {
            context = new KBSQLClassDataContext();
            var timeSlot = from fc in context.TimeSlots select fc;            
            dataGridView5.DataSource = timeSlot;
            dataGridView5.Columns[0].HeaderText = "Mã số";
            dataGridView5.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            dataGridView5.Columns[1].HeaderText = "Tên ca";
            dataGridView5.Columns[2].HeaderText = "Giờ bắt đầu";
            dataGridView5.Columns[3].HeaderText = "Giờ kết thúc";
            try
            {
                dataGridView5.CurrentCell = dataGridView5[0, grvTimeSlotIndex];
            }
            catch (Exception)
            { }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            Boolean isValid = validateError();
            if (!isValid)
            {
                return;
            }
            int month = DateTime.Now.Month;
            int year = DateTime.Now.Year;
            Pay_Salary paySalary = context.Pay_Salaries.SingleOrDefault(ps=>ps.PayMonth == month && ps.PayYear == year);
            if (paySalary == null)
            {
                MessageBox.Show("Bảng lương tháng "+month +" năm "+year +"chưa được tạo liên hệ người có trách nhiệm để tạo bảng lương");
                return;
            }
            var detailPenalty = new Penalty_Detail
            {
                PsId = paySalary.PsId,
                PenaltyID = Convert.ToInt32(cbbNamePenalty.SelectedValue.ToString()),
                Description = richTextBox2.Text,
                Status = true,
                PenaltyDate = Convert.ToDateTime(DateTime.Now.ToShortDateString())
            };
            ConfirmManageDaily confirm = new ConfirmManageDaily(lblNameEmpl.Text, lblIdEmpl.Text, cbbNamePenalty.Text);
            if (confirm.ShowDialog() == DialogResult.OK)
            {
                context.Penalty_Details.InsertOnSubmit(detailPenalty);
                context.SubmitChanges();
                transactionLog.TransactionLogCommon("Nhân viên "+AdminSession.admin.UserName+" đã lưu thông tin lỗi "+cbbNamePenalty.SelectedText+" ngày " + DateTime.Now.ToString() + " của nhân viên " + lblNameEmpl.Text);
                MessageBox.Show("Thông tin lỗi ngày " + DateTime.Now.ToString() + " của nhân viên " + lblNameEmpl.Text + " Đã lưu thành công");
                richTextBox2.Text = "";
                SelectDetailPenalty();
            }
        }

        private bool validateError()
        {
            if(cbbNamePenalty.SelectedIndex<0)
            {
                MessageBox.Show("Hãy lựa chọn lỗi");
                return false;
            }
            return true;
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            SearchDetailPenalty(txtSearchName.Text, dtpFrom.Value, dtpTo.Value);
        }

     

        private void tsbReportDetailPenalty_Click(object sender, EventArgs e)
        {
            new ReportDetaiPenalty(detailPenalty).Show();
        }

        private void btnStock_Click(object sender, EventArgs e)
        {
            new ReportEmployee(employeeQuery).Show();
        }

        private void sửaThôngTinToolStripMenuItem_Click(object sender, EventArgs e)
        {
            EditEmployee();
        }

        private void EditEmployee()
        {
            if (dgvEmployee.SelectedRows.Count > 0)
            {
                Employee employee = new EmployeeFacade().Find(dgvEmployee.SelectedRows[0].Cells[0].Value.ToString());
                new EditEmployee(employee).ShowDialog();
            }
        }

        public void Update()
        {
            SelectEmployee();
            SelectTimeSlot();
        }

        public void SetHeaderDetailPenalty()
        {
            dataGridView4.Columns[0].HeaderText = "Mã số";
            dataGridView4.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            dataGridView4.Columns[1].HeaderText = "Họ tên";
            dataGridView4.Columns[2].HeaderText = "Miêu tả";
            dataGridView4.Columns[3].HeaderText = "Tình trạng";
            dataGridView4.Columns[4].HeaderText = "Ngày vi phạm";
            dataGridView4.Columns[5].HeaderText = "Tên lỗi vi phạm";  
        }


        private void SelectEmployee()
        {
            var employee = from fc in context.Employees
                           select new
                           {
                               fc.ID,
                               fc.FullName,
                               fc.Email,
                               fc.Address,
                               fc.BirthDay,
                               fc.Gender,
                               fc.Phone,
                               fc.Position.Ps_Name,
                               fc.TimeSlot.StartTime,
                               fc.TimeSlot.EndTime
                           };

            dgvEmployee.DataSource = employee;
            dgvEmployee.Columns[0].HeaderText = "Mã số";
            dgvEmployee.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            dgvEmployee.Columns[1].HeaderText = "Họ tên";
            dgvEmployee.Columns[2].HeaderText = "Thư điện tử";
            dgvEmployee.Columns[3].HeaderText = "Địa chỉ";
            dgvEmployee.Columns[4].HeaderText = "Ngày sinh";
            dgvEmployee.Columns[5].HeaderText = "Giới tính";
            dgvEmployee.Columns[6].HeaderText = "Điện thoại";
            dgvEmployee.Columns[7].HeaderText = "Chức vụ";
            dgvEmployee.Columns[8].HeaderText = "Giờ bắt đầu ca";
            dgvEmployee.Columns[9].HeaderText = "Giờ kết thúc ca";
            employeeQuery = from fc in context.Employees select fc;
            try
            {
                dgvEmployee.CurrentCell = dgvEmployee[0, dgvEmployeeIndex];
            }
            catch (Exception)
            { 
                
            }
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            AddTimeSlot();
        }

        private void AddTimeSlot()
        {
            AddEditTimeSlot empl = new AddEditTimeSlot(null);
            empl.ShowDialog();
        }

        private void UpdateTimeSlot()
        {
            if (dataGridView5.SelectedRows.Count > 0)
            {
                try
                {
                    TimeSlot tSlot = timeSlotFacade.Find(dataGridView5.SelectedRows[0].Cells[0].Value);
                    AddEditTimeSlot empl = new AddEditTimeSlot(tSlot);
                    empl.ShowDialog();
                }
                catch (Exception)
                {
                }
                
            }
            
        }

        private void thêmToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AddTimeSlot();
        }

        private void dataGridView5_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            toolStripBtnEdit.Enabled = true;
            grvTimeSlotIndex = e.RowIndex;
        }

        private void toolStripBtnEdit_Click(object sender, EventArgs e)
        {
            UpdateTimeSlot();
        }

        private void dgvEmployee_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                lblIdEmpl.Text = dgvEmployee.Rows[e.RowIndex].Cells[0].Value.ToString();
                lblNameEmpl.Text = dgvEmployee.Rows[e.RowIndex].Cells[1].Value.ToString();
                cbbNamePenalty.Enabled = true;
                toolStripBtnEditEmpl.Enabled = true;
            }
            catch (Exception)
            { }
        }

        private void toolStripBtnTip_Click(object sender, EventArgs e)
        {
            if (dgvEmployee.SelectedRows.Count > 0)
            {
                Employee empl = employeeFacade.Find(dgvEmployee.SelectedRows[0].Cells[0].Value);
                AddTipMoney addTipMoney = new AddTipMoney(empl);
                addTipMoney.ShowDialog();
            }
        }

        private void toolStripAddEmp_Click(object sender, EventArgs e)
        {
            AddEmployee();
        }

        private static void AddEmployee()
        {
            AddEmployee addEmployee = new AddEmployee();
            addEmployee.ShowDialog();
        }

        private void thêmToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            AddEmployee();
        }

        private void cbbNamePenalty_SelectedValueChanged(object sender, EventArgs e)
        {
            btnAddPenalty.Enabled = true;
        }

        private void chiTiếtLỗiTrongThángToolStripMenuItem_Click(object sender, EventArgs e)
        {

            if (dgvEmployee.SelectedRows.Count > 0)
            {
                int month = DateTime.Now.Month;
                int year = DateTime.Now.Year;
                string EmployeeId = dgvEmployee.SelectedRows[0].Cells[0].Value.ToString();
                DateTime dateTo = DateTo(month, year);
                DateTime dateFrom = new DateTime(year, month, 1);
               
                var detail = from fc in context.Penalty_Details
                                where fc.Pay_Salary.Employee.ID == EmployeeId && fc.PenaltyDate >= dateFrom && fc.PenaltyDate <= dateTo
                                select fc;
                new ReportDetaiPenalty(detail).Show();
            }
        }

        public DateTime DateTo(int month, int year)
        {
            DateTime dateTo = DateTime.Now;
            try
            {
                dateTo = new DateTime(year, month, 31);
            }
            catch (Exception)
            {
                try
                {
                    dateTo = new DateTime(year, month, 30);
                }
                catch (Exception)
                {
                    try
                    {
                        dateTo = new DateTime(year, month, 29);
                    }
                    catch (Exception)
                    {
                        dateTo = new DateTime(year, month, 28);
                    }
                }
            }

            return dateTo;
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            int month = DateTime.Now.Month;
            int year = DateTime.Now.Year;
            DateTime dateFrom = new DateTime(year, month, 1);
            DateTime dateTo = DateTo(month,year);
            if (comboBox1.SelectedIndex == 0)
            {
                dateFrom = DateTime.Now.AddDays(-1);
                dateTo = DateTime.Now;
            }
            if (comboBox1.SelectedIndex == 1)
            {
                dateFrom = new DateTime(year, month, 1);
                dateTo = DateTo(month, year);
            }
            if (comboBox1.SelectedIndex == 2)
            {
                dateFrom = new DateTime(year, 1, 1);
                dateTo = DateTo(12, year);
            }
            
            var detailPena = from fc in context.Penalty_Details
                             where fc.PenaltyDate >= dateFrom && fc.PenaltyDate <= dateTo
                             select new
                             {
                                 fc.ID,
                                 fc.Pay_Salary.Employee.FullName,
                                 fc.Description,
                                 fc.Status,
                                 fc.PenaltyDate,
                                 fc.Penalty.Pe_Name
                             }
           ;
            dataGridView4.DataSource = detailPena;
            SetHeaderDetailPenalty();

            //Get data for Print
            detailPenalty = from fc in context.Penalty_Details
                            where fc.PenaltyDate >= dateFrom && fc.PenaltyDate <= dateTo
                            select fc;            
        }

        private void toolStripBtnEditEmpl_Click(object sender, EventArgs e)
        {
            EditEmployee();
        }

        private void sửaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            UpdateTimeSlot();
        }
    }
}
